package com.uduemc.biso.node.module.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.uduemc.biso.node.core.entities.HWatermark;
import com.uduemc.biso.node.module.mapper.HWatermarkMapper;
import com.uduemc.biso.node.module.service.HWatermarkService;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class HWatermarkServiceImpl implements HWatermarkService {

	@Autowired
	private HWatermarkMapper hWatermarkMapper;

	@Override
	public HWatermark insertAndUpdateCreateAt(HWatermark hWatermark) {
		hWatermarkMapper.insert(hWatermark);
		HWatermark findOne = findOne(hWatermark.getId());
		Date createAt = hWatermark.getCreateAt();
		if (createAt != null) {
			hWatermarkMapper.updateCreateAt(findOne.getId(), createAt, HWatermark.class);
		}
		return findOne;
	}
	
	@Override
	public HWatermark findIfNotExistByHostId(Long hostId) {
		Example example = new Example(HWatermark.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		example.setOrderByClause("`id` DESC");

		PageHelper.startPage(1, 1);
		HWatermark hWatermark = hWatermarkMapper.selectOneByExample(example);
		if (hWatermark != null) {
			return hWatermark;
		}
		hWatermark = new HWatermark();
		hWatermark.setHostId(hostId).setRepertoryId(0L).setType(1).setText("").setFont("宋体").setFontsize(12).setBold(0).setColor("#000000").setSize(100)
				.setOpacity(100).setArea(9);

		hWatermarkMapper.insert(hWatermark);

		return findOne(hWatermark.getId());
	}

	@Override
	public HWatermark findOne(Long id) {
		return hWatermarkMapper.selectByPrimaryKey(id);
	}

	@Override
	public HWatermark updateById(HWatermark hWatermark) {
		hWatermarkMapper.updateByPrimaryKey(hWatermark);
		return findOne(hWatermark.getId());
	}

	@Override
	public int deleteByHostId(long hostId) {
		Example example = new Example(HWatermark.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		return hWatermarkMapper.deleteByExample(example);
	}

}
